<!--
 * @Author: 王灿
 * @Date: 2019-11-10 16:10:08
 * @LastEditTime: 2020-03-16 19:47:27
 * @Description: 商品详情
 * @FilePath: \scarlet-sparrow-admin\src\views\commodity\commodity-details\index.vue
 -->
 <template>
  <div class="commodity-details">
    <happy-scroll color="rgba(0,0,0,0.05)" size="5" class="commodity-details__wrapper">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="el-form__details">
        <el-form-item prop="name">
          <el-input v-model="ruleForm.name" placeholder="商品名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="ruleForm.type"
            clearable
            placeholder="礼包类型"
            style="margin-right: 10px;"
            @change="onChangeSelect"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-select v-model="ruleForm.upperShelfFlag" clearable placeholder="商品状态">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <div class="commodity-details__row">
          <el-form-item prop="markPrice">
            <el-input placeholder="标价" v-model="ruleForm.markPrice" clearable></el-input>
          </el-form-item>
          <el-form-item prop="actualPrice">
            <el-input placeholder="实际价格" v-model="ruleForm.actualPrice" clearable></el-input>
          </el-form-item>
          <el-form-item prop="sales">
            <el-input placeholder="累计销量" v-model="ruleForm.sales" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-input placeholder="返佣比例" v-model="ruleForm.selfPurchase"></el-input>
          </el-form-item>
        </div>
        <div class="commodity-details__row">
          <!--<el-form-item prop="stock">
                        <el-input placeholder="商品库存" v-model="ruleForm.stock" clearable></el-input>
                        </el-form-item>
                        <el-form-item prop="noVipRakeBack">
                        <el-input placeholder="返佣金额" v-model="ruleForm.noVipRakeBack" clearable></el-input>
          </el-form-item>-->
        </div>
        <el-form-item prop="introduce" class="el-form-textarea">
          <el-input
            type="textarea"
            maxlength="100"
            :autosize="{ minRows: 1, maxRows: 2}"
            placeholder="商品介绍"
            v-model="ruleForm.introduce"
          ></el-input>
        </el-form-item>
        <!-- 上传组件 -->
        <el-form-item>
          <jq-upload :upData="mainPicObj" :fileList="mainPic" @onChangeImageKey="onChangeImageKey" />
        </el-form-item>
        <el-form-item>
          <jq-upload
            :upData="detailPicObj"
            :fileList="detailPic"
            @onChangeImageKey="onChangeImageKey"
          />
        </el-form-item>
        <el-form-item>
          <jq-upload :upData="homePicObj" :fileList="homePic" @onChangeImageKey="onChangeImageKey" />
        </el-form-item>
      </el-form>
      <!-- 富文本 -->
      <div class="el-form__quill">
        <jq-tinymce
          ref="editor"
          v-model="ruleForm.detailsIntroduce"
          :isUpdate="isUpdate"
          :minHeight="827"
          @input="onGetEditorValue"
        />
      </div>
    </happy-scroll>
    <div class="commodity-details__btns dialog-footer">
      <el-button type="primary" @click="onSubmitGift">礼 包</el-button>
      <el-button type="primary" @click="onSubmitForm('ruleForm')">确 定</el-button>
      <el-button @click="onCancelForm('ruleForm')">取 消</el-button>
    </div>

    <!-- 抽屉 -->
    <el-drawer
      title="配置礼包"
      :visible.sync="isShow"
      :wrapperClosable="false"
      :destroyOnClose="true"
      :show-close="show"
      direction="rtl"
      @open="onOpen"
      @close="onClose"
      @opened="onOpened"
      @closed="onClosed"
      size="80%"
      height="90%"
      ref="drawer"
    >
      <!-- 配置vip -->
      <vip-operate
        :propertyName="propertyName"
        :propertyValue="propertyValue"
        @onCancelBtn="onCancelBtn"
      />
    </el-drawer>
  </div>
</template>

 <script>
import JqTinymce from '@/components/jq-tinymce/index.vue'
import JqUpload from '@/components/jq-upload/index.vue'
import {
  getGiftPackageAdd,
  getGiftPackageUpdate,
  getUploadKey,
  getDownUrl
} from '@/api/commodity.js'
import { Message } from 'element-ui'
import { storageSetItem, storageGetItem } from '@/utils/index.js'
import VipOperate from '@/views/configure/configure-vip/vip-operate/index.vue'
export default {
  name: 'CommodityDetails',
  components: { JqUpload, JqTinymce, VipOperate },
  props: {
    // 行数据
    row: {
      ttype: Object,
      default: () => {
        return {}
      }
    },
    // 商品类型
    commodityType: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      activeName: 'first',
      // 上传对象
      ruleForm: {
        id: '',
        name: '',
        type: '',
        upperShelfFlag: 1,
        introduce: '',
        detailsIntroduce: '',
        mainPic: '',
        detailPic: '',
        homePic: '',
        markPrice: '',
        actualPrice: '',
        // stock: '',
        sales: '',
        // noVipRakeBack: '',
        selfPurchase: '',
        propertyValue: ''
      },
      defaultForm: {},
      // 商品主图
      mainPicObj: {
        label: '商品主图',
        accept: 'image/png, image/gif, image/jpg, image/jpeg',
        limit: 1,
        type: 1,
        isImage: true
      },
      // 商品详情主图
      detailPicObj: {
        label: '详情页主图',
        accept: 'image/png, image/gif, image/jpg, image/jpeg',
        limit: 5,
        type: 2,
        isImage: true
      },
      // 首页图片
      homePicObj: {
        label: '首页主图',
        accept: 'image/png, image/gif, image/jpg, image/jpeg',
        limit: 1,
        type: 3,
        isImage: true
      },
      // 商品类型
      typeOptions: [
        {
          value: 0,
          label: '特惠礼包'
        },
        {
          value: 1,
          label: '超级会员礼包'
        },
        {
          value: 2,
          label: '社群团长礼包'
        },
        {
          value: 3,
          label: '联盟服务商礼包'
        },
        {
          value: 4,
          label: '城市合伙人礼包'
        }
      ],
      // 商品状态
      statusOptions: [
        {
          value: 0,
          label: '下架'
        },
        {
          value: 1,
          label: '上架'
        }
      ],
      // 正则
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        type: [
          { required: true, message: '请选择商品类型', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输入商品介绍', trigger: 'blur' }
        ],
        markPrice: [
          { required: true, message: '请输入标价', trigger: 'blur' },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '输入两位小数',
            trigger: 'blur'
          }
        ],
        actualPrice: [
          { required: true, message: '请输入实际价格', trigger: 'blur' },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '输入两位小数',
            trigger: 'blur'
          }
        ],
        stock: [
          { required: true, message: '请输入库存', trigger: 'blur' },
          {
            pattern: /^[1-9]\d*$/,
            message: '库存必须为数字值',
            trigger: 'blur'
          }
        ],
        sales: [
          { required: true, message: '请输入销量数', trigger: 'blur' },
          {
            pattern: /^[1-9]\d*$/,
            message: '销量必须为数字值',
            trigger: 'blur'
          }
        ],
        noVipRakeBack: [
          { required: true, message: '请输入返佣金额', trigger: 'blur' },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '输入两位小数',
            trigger: 'blur'
          }
        ],
        // selfPurchase: [
        //   {required: true, message: '请输入返佣比例', trigger: 'blur'},
        //   { pattern: /^0\.[1-9]\d{0,1}$/, message: '输入两位小数', trigger: 'blur' }
        // ],
        propertyValue: [
          { required: true, message: '请配置礼包', trigger: 'blur' }
        ]
      },
      isUpdate: false,
      mainPic: [],
      detailPic: [],
      homePic: [],
      isShow: false,
      show: false,
      propertyName: '',
      propertyValue: []
    }
  },
  watch: {
    // 监听数据变化
    row() {
      this.isUpdate = false
      this.onGetRow()
    }
  },
  created() {
    // 初始化
    this.defaultForm = JSON.parse(JSON.stringify(this.ruleForm))
    // 取默认 只触发一次
    this.onGetRow()
  },
  methods: {
    // 礼包类型切换
    onChangeSelect(val) {
      storageSetItem('propertyData', [])
    },
    // 打开 -- 动画结束回调
    onOpen() {
      // some
    },
    onOpened() {
      this.show = true
    },
    // 关闭 -- 动画结束回调
    onClose() {
      this.show = false
    },
    onClosed() {
      this.show = false
    },
    // 编辑时 取默认值
    onGetRow() {
      this.mainPic = []
      this.detailPic = []
      if (JSON.stringify(this.row) !== '{}') {
        this.ruleForm = {
          id: this.row.id,
          name: this.row.name,
          type: Number(this.row.type),
          upperShelfFlag: this.row.upperShelfFlag,
          introduce: this.row.introduce,
          detailsIntroduce: this.row.detailsIntroduce,
          mainPic: this.row.mainPic,
          detailPic: this.row.detailPic,
          homePic: this.row.homePic,
          markPrice: this.row.markPrice,
          actualPrice: this.row.actualPrice,
          // stock: this.row.stock,
          sales: this.row.sales,
          // noVipRakeBack: this.row.noVipRakeBack,
          selfPurchase: this.row.selfPurchase,
          propertyValue: this.row.propertyValue
        }
        // 下载详情图片
        let _resultPic = this.row.detailPic.split(',')
        _resultPic.forEach(pic => {
          getDownUrl({
            fileName: pic
          }).then(res => {
            this.detailPic.push({ name: pic, url: res.data.url.split('?')[0] })
          })
        })
        // 下载商品主图
        getDownUrl({
          fileName: this.row.mainPic
        }).then(res => {
          this.mainPic.push({
            name: this.row.detailPic,
            url: res.data.url.split('?')[0]
          })
        })
        // 首页图片
        getDownUrl({
          fileName: this.row.homePic
        }).then(res => {
          this.homePic.push({
            name: this.row.homePic,
            url: res.data.url.split('?')[0]
          })
        })
      }
    },
    // 赋值富文本
    onGetEditorValue(data) {
      this.isUpdate = true
      this.ruleForm.detailsIntroduce = data
    },
    // 子组件传值
    onChangeImageKey(fileName, type, isDetele, url) {
      if (isDetele) {
        if (type === 2) {
          if (this.ruleForm.detailPic.indexOf(',') === 0) {
            this.ruleForm.detailPic = this.ruleForm.detailPic
              .substr(1)
              .split(',')
              .filter(value => value !== fileName)
              .join(',')
          } else {
            this.ruleForm.detailPic = this.ruleForm.detailPic
              .split(',')
              .filter(value => value !== fileName)
              .join(',')
          }
          this.detailPic = this.detailPic.filter(item => item.name !== fileName)
        } else if (type === 1) {
          this.ruleForm.mainPic = fileName
          this.mainPic = this.mainPic.filter(item => item.name !== fileName)
        } else {
          this.ruleForm.homePic = fileName
          this.homePic = this.homePic.filter(item => item.name !== fileName)
        }
      } else {
        if (type === 1) {
          this.ruleForm.mainPic = fileName
          if (url) {
            this.mainPic.push({ name: fileName, url: url })
          }
        } else if (type === 2) {
          this.ruleForm.detailPic += ',' + fileName
          if (url) {
            this.detailPic.push({ name: fileName, url: url })
          }
        } else if (type === 3) {
          this.ruleForm.homePic = fileName
          if (url) {
            this.homePic.push({ name: fileName, url: url })
          }
        }
      }
    },
    // 礼包
    onSubmitGift() {
      if (this.ruleForm.type === '') {
        this.$message.error('请先选择礼包类型')
      } else {
        this.isShow = true
        this.propertyName = this.typeOptions[this.ruleForm.type].label
        let propertyData = storageGetItem('propertyData')
        this.propertyValue =
          propertyData.length === 0
            ? []
            : JSON.parse(propertyData[0].propertyValue)
      }
    },
    // 提交
    onSubmitForm(formName) {
      if (storageGetItem('propertyData').length === 0) {
        this.$message.error('请先配置礼包')
        return false
      } else {
        this.ruleForm.propertyValue = JSON.stringify(
          storageGetItem('propertyData')
        )
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (
            this.ruleForm.mainPic === '' ||
            this.ruleForm.detailPic === '' ||
            this.ruleForm.homePic === ''
          ) {
            this.$message.error('请上传图片')
            return false
          }
          if (this.ruleForm.detailPic.indexOf(',') === 0) {
            this.ruleForm.detailPic = this.ruleForm.detailPic.substr(1)
          }
          if (this.ruleForm.id) {
            // 编辑
            getGiftPackageUpdate(this.ruleForm).then(res => {
              this.ruleForm = JSON.parse(JSON.stringify(this.defaultForm))
              this.$emit('onCancelBtn', { isShow: false, isRefresh: true })
              this.$message({
                message: '编辑商品成功',
                type: 'success'
              })
            })
          } else {
            // 新增
            getGiftPackageAdd(this.ruleForm).then(res => {
              this.ruleForm = JSON.parse(JSON.stringify(this.defaultForm))
              this.$emit('onCancelBtn', { isShow: false, isRefresh: true })
              this.$message({
                message: '新增商品成功',
                type: 'success'
              })
            })
          }
        }
      })
    },
    // 取消
    onCancelForm(formName) {
      this.$refs[formName].resetFields()
      this.ruleForm = JSON.parse(JSON.stringify(this.defaultForm))
      this.$emit('onCancelBtn', { isShow: false, isRefresh: false })
    },
    // 礼包 取消 / 成功
    onCancelBtn(data) {
      this.propertyValue = []
      this.isShow = data.isShow
      this.isRefresh = data.isRefresh
    }
  }
}
</script>

 <style lang="scss">
.commodity-details {
  @include column;
  height: 100%;
  position: relative;
  .commodity-details__wrapper {
    overflow: hidden;
    display: flex;
    .commodity-details__row {
      width: 100%;
      @include row;
      justify-content: space-between;
      .el-form-item {
        flex: 1 !important;
      }
    }
    .el-form__details {
      width: 50%;
      height: 100%;
      @include column;
      .el-select {
        width: 100%;
      }
    }
    .el-form__quill {
      flex: 1;
      height: 100%;
    }
  }
  .commodity-details__btns {
    padding-top: 10px;
    box-shadow: 0 -2px 2px #ececec;
  }
}
</style>
